package wxwoa

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"

	"gitee.com/chenrh/finego/backends/utils"
	"github.com/kataras/iris/v12"
)

// WxAccessToken 1
type WxAccessToken struct {
	// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
}

// AccessToken 返回 AccessToken
func (c WxAccessToken) AccessToken(ctx iris.Context) string {
	appid := WeChatSubscriptionAppID(ctx)
	appsecret := WeChatSubscriptionAppSecret(ctx)
	ok, token := c.TryGetAccessToken(appid, appsecret)
	if ok {
		return token
	}
	return ""
}

// TryGetAccessToken 获取 AccessToken
func (c WxAccessToken) TryGetAccessToken(appid, appsecret string) (bool, string) {
	// 1. 先从缓存里找，如果没有再去请求接口
	_token := utils.GetCache(WX_CACHEKEY_ACCESS_TOKEN)
	if _token != nil {
		return true, _token.(string)
	}

	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appid, appsecret)
	resp, err := http.Get(url)
	if err != nil {
		return false, err.Error()
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	content := string(body)
	log.Println("-- 获取 ", WX_CACHEKEY_ACCESS_TOKEN, " 接口返回：", content)

	var jsonmap map[string]interface{}
	json.Unmarshal([]byte(content), &jsonmap)

	if _, ok := jsonmap["access_token"]; ok {
		if jsonmap["access_token"] != nil {
			/*
				参数			说明
				access_token	获取到的凭证
				expires_in		凭证有效时间，单位：秒
			*/
			token := jsonmap["access_token"].(string)
			expires_in := jsonmap["expires_in"].(float64)
			expire := time.Duration(expires_in) * time.Second

			utils.SetCache(WX_CACHEKEY_ACCESS_TOKEN, token, expire)

			return true, token
		} else {
			return false, "微信接口返回空 access_token"
		}
		// model.ACCESS_TOKEN = jsonmap["access_token"].(string)
		// model.ACCESS_TIME = time.Now()
		// model.EXPIRES_IN = jsonmap["expires_in"].(float64)
		// model.ERRCODE = 0
		// model.ERRMSG = "请求成功"
	} else if _, ok := jsonmap["errcode"]; ok {
		return false, content
	}
	return false, content
}
